In [2]:
N = 2000000
prime = [True] * N
prime_sum = 0
for p in range(2, N):
if prime[p]:
prime_sum += p
for m in range(p*p, N, p):
prime[m] = False
print(prime_sum)
Explanation: We use the sieve of Eratosthenes to find all primes less than two million.
If $p$ is prime, then we add $p$ to prime_sum
, and we mark all multiples of $p$ as composite,
starting with $p^2$. The reason that we can start with $p^2$ is that all smaller multiples of $p$
will have been marked already.
We could speed up this program by iterating through the odd numbers.
Alternative solution:
In [3]:
from primesieve import primes
print(sum(primes(N)))
In [ ]: